import * as vscode from 'vscode';
import axios from 'axios';

export function registerTestProgressBarCommand(
  context: vscode.ExtensionContext
) {
  /**
   * 注册测试进度条命令
   */
  const disposable = vscode.commands.registerCommand(
    'cw-vscode-ai.testProgressBar',
    async () => {
      try {
        // 显示进度指示器
        await vscode.window.withProgress(
          {
            location: vscode.ProgressLocation.Window,
            title: '测试进度条...',
            cancellable: true,
          },
          async (progress) => {
            try {
              console.log('进度通知已创建');

              // 初始进度
              progress.report({ increment: 0, message: '开始测试...' });
              await new Promise((resolve) => setTimeout(resolve, 500));

              // 第一阶段
              progress.report({ increment: 30, message: '第一阶段...' });
              await new Promise((resolve) => setTimeout(resolve, 1000));

              // 第二阶段
              progress.report({ increment: 40, message: '第二阶段...' });
              await new Promise((resolve) => setTimeout(resolve, 1000));

              // 完成
              progress.report({ increment: 30, message: '完成！' });
              await new Promise((resolve) => setTimeout(resolve, 500));

              console.log('进度条测试完成');
            } catch (error: any) {
              console.error('进度条测试失败:', error);
              vscode.window.showErrorMessage(`测试失败: ${error.message}`);
            }
          }
        );

        // 显示成功消息
        vscode.window.showInformationMessage('进度条测试完成!');
      } catch (progressError: any) {
        console.error('创建进度条失败:', progressError);
        vscode.window.showErrorMessage(
          `无法创建进度指示器: ${progressError.message}`
        );
      }
    }
  );
  return disposable;
}

/**
 *  注册 explainCode 命令
 * @param context 全局上下文
 * @returns 注册 explainCode 命令 的方法
 */
export function registerExplainCodeCommand(context: vscode.ExtensionContext) {
  const disposable = vscode.commands.registerCommand(
    'cw-vscode-ai.explainCode',
    async (text: string, uri: string, range: vscode.Range) => {
      // 验证参数
      if (!text) {
        vscode.window.showErrorMessage('没有提供要解释的代码内容');
        return;
      }

      try {
        // 显示进度指示器
        await vscode.window.withProgress(
          {
            location: vscode.ProgressLocation.Window,
            title: '正在分析代码...',
            cancellable: false,
          },
          async (progress) => {
            try {
              progress.report({ increment: 0, message: '准备中...' });
              // 确保在UI更新后再继续
              await new Promise((resolve) => setTimeout(resolve, 100));
              progress.report({ increment: 30, message: '正在发送请求...' });

              // 创建和显示 Webview
              const panel = vscode.window.createWebviewPanel(
                'codeExplanation',
                '代码解释',
                vscode.ViewColumn.Beside,
                {
                  enableScripts: true,
                  retainContextWhenHidden: true,
                }
              );

              // 设置初始 HTML 内容
              panel.webview.html = `
                <!DOCTYPE html>
                <html>
                <head>
                    <meta charset="UTF-8">
                    <meta name="viewport" content="width=device-width, initial-scale=1.0">
                    <title>代码解释</title>
                    <style>
                        body { font-family: Arial, sans-serif; padding: 20px; }
                        pre { background-color: #f5f5f5; padding: 10px; border-radius: 5px; overflow-x: auto; }
                        .code-block { margin-bottom: 20px; }
                        .explanation { line-height: 1.6; white-space: pre-wrap; }
                    </style>
                </head>
                <body>
                    <h2>原始代码</h2>
                    <div class="code-block">
                        <pre>${escapeHtml(text)}</pre>
                    </div>
                    <h2>代码解释</h2>
                    <div class="explanation" id="explanation"></div>
                    <script>
                        const vscode = acquireVsCodeApi();
                        window.addEventListener('message', event => {
                            const message = event.data;
                            if (message.type === 'append') {
                                const explanationDiv = document.getElementById('explanation');
                                explanationDiv.textContent += message.content;
                            }
                        });
                    </script>
                </body>
                </html>
              `;

              // 处理流式响应
              const response = await axios.post(
                'https://api.deepseek.com/chat/completions',
                {
                  model: 'deepseek-chat',
                  messages: [{ role: 'system', content: `解释代码:\n${text}` }],
                  stream: true,
                  files: '',
                },
                {
                  headers: {
                    'Content-Type': 'application/json',
                    Authorization: 'Bearer sk-de11e7d34ff2413c9228e583a937865b',
                  },
                  responseType: 'stream',
                }
              );

              response.data.on('data', (chunk: Buffer) => {
                const decodedChunk = chunk.toString('utf8');
                if (decodedChunk.includes('data:')) {
                  const data = decodedChunk.split('data:')[1].trim();
                  if (data !== '[DONE]') {
                    const parsedData = JSON.parse(data);
                    const text = parsedData.choices[0].delta.content;
                    if (text) {
                      // 解析流式数据并发送到 Webview
                      panel.webview.postMessage({
                        type: 'append',
                        content: text,
                      });
                    }
                  }
                }
              });

              response.data.on('end', () => {
                console.log('流式响应结束');
                panel.webview.postMessage({
                  type: 'append',
                  content: '\n[完成]',
                });
              });

              response.data.on('error', (error: any) => {
                console.error('流式响应错误:', error);
                vscode.window.showErrorMessage(
                  `流式响应失败: ${error.message}`
                );
              });

              progress.report({ increment: 100, message: '完成！' });
            } catch (error: any) {
              console.error('解释代码失败:', error);
              vscode.window.showErrorMessage(`解释代码失败: ${error.message}`);
            }
          }
        );
      } catch (progressError: any) {
        console.error('创建进度条失败:', progressError);
        vscode.window.showErrorMessage(
          `无法创建进度指示器: ${progressError.message}`
        );
      }
    }
  );

  // 返回 disposable 以便在 extension.ts 中添加到 context.subscriptions
  return disposable;
}

function extractDataObject(data: string): object | null {
  try {
    // 找到 "data:" 的位置
    const dataIndex = data.indexOf('data:');
    if (dataIndex === -1) {
      console.error('未找到 "data:" 标记');
      return null;
    }

    // 提取 "data:" 后面的部分并去掉多余的空格
    const jsonString = data.substring(dataIndex + 5).trim();

    // 将提取的部分解析为 JSON 对象
    return JSON.parse(jsonString);
  } catch (error) {
    console.error('解析数据失败:', error);
    return null;
  }
}

// 辅助函数：转义HTML
function escapeHtml(text: any) {
  if (typeof text !== 'string') {
    console.warn('escapeHtml 接收到非字符串值:', text);
    text = String(text || '');
  }
  return text
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#039;');
}
